package org.ank.food;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class LastAdviceActivity extends Activity{
	
	public final static int NEW_ADVICE = 0;
	public final static int EXISTING_ADVICE = 1;
	public final static String ADVICE_EXTRA_NAME = "advice extra";
	private TextView exceedingTextView;
	private final static int MENU_ITEM_ADD_TO_EATEN = Menu.FIRST; 
	
	public ListView listView;
	private Button newAdviceButton, exitButton;
	SimpleCursorAdapter adapter = null;
	
	@Override
	public void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.last_advice_activity);
		listView = (ListView)findViewById(R.id.last_advice_list);
		listView.setOnCreateContextMenuListener(this);
		
		Cursor cursor = AdviceManager.getInstance(getApplicationContext()).getLastAdviceCursor();
		cursor.moveToFirst();
		if (cursor.getCount() == 0){
//			Log.v("last advice","no information");
			Intent intent = new Intent();
    		intent.setClass(getApplicationContext(), EatenTodayActivity.class);
    		startActivity(intent);
    		finish();
		}
		adapter = new SimpleCursorAdapter(getApplicationContext(),
				android.R.layout.simple_list_item_1, cursor, 
				new String[]{AdviceProvider.COLUMN_NAMES[AdviceProvider.PRODUCT_NAME]},
				new int[]{android.R.id.text1});
		listView.setAdapter(adapter);
		
		exceedingTextView = (TextView)findViewById(R.id.last_advice_exceeding_textview);
		newAdviceButton = (Button)findViewById(R.id.last_advice_newadvice_button);
		newAdviceButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
//				Log.v("lsat advise","new advice clicked");
				
							Intent intent = new Intent();
				    		intent.setClass(getApplicationContext(), EatenTodayActivity.class);
				    		startActivity(intent);
				    		finish();
				
			}
		});
		exitButton = (Button)findViewById(R.id.last_advice_exit_button);
		exitButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
	    		intent.setClass(getApplicationContext(), ProfileChooseActivity.class);
	    		startActivity(intent);
	    		finish();
			}
		});

		final ProgressBar progressBar = (ProgressBar)findViewById(R.id.last_advice_progress_bar);
		final TextView pleaseWaitTextView = (TextView)findViewById(R.id.last_advice_please_wait_textview);
		Intent parentIntent = getIntent();
		int adviceMode = parentIntent.getIntExtra(ADVICE_EXTRA_NAME, EXISTING_ADVICE);
		if(adviceMode == NEW_ADVICE){
			if(adapter == null)
				Log.v("create handler", "adapter is null");
			else
				Log.v("create handler", "adapter is"+adapter);
			AdviceRequestHandler handler = new AdviceRequestHandler(progressBar, pleaseWaitTextView, 
					listView,adapter,getApplicationContext(),newAdviceButton,exitButton);
			showNewAdvice(listView, handler);
			return;
		}
		
	}
	private void showNewAdvice(/*final int initialExceedingStringId, String[] exceedingStrings,*/ 
			final ListView listView, AdviceRequestHandler h){
		
		final AdviceRequestHandler handler = h;
		
		Thread t = new Thread(new Runnable(){
			@Override
			public void run() {
				Message m = Message.obtain(handler, AdviceRequestHandler.WAIT);
				m.sendToTarget();
				int[] exceedings = AdviceManager.getInstance(getApplicationContext()).makeAdvice();
				AdviceManager.getInstance(getApplicationContext()).setExceedings(exceedings);
				StringBuffer buf = new StringBuffer(getString(R.string.quotas_excedeed_string));
				boolean exceeded = false;
				if (exceedings[0] == 1){
					buf.append('\n').append(getString(R.string.quotas_proteins_name));
					exceeded = true;
				}
				if (exceedings[1] == 1){
					buf.append('\n').append(getString(R.string.quotas_fat_name));
					exceeded = true;
				}
				if (exceedings[2] == 1){
					buf.append('\n').append(getString(R.string.quotas_carbo_name));
					exceeded = true;
				}
				AdviceManager.getInstance(getApplicationContext()).setExceedings(exceedings);
				if(exceeded){
					exceedingTextView.setText(buf.toString());
					exceedingTextView.setVisibility(TextView.VISIBLE);
					m = Message.obtain(handler, AdviceRequestHandler.READY);
					m.sendToTarget();
					return;
				}
//				Cursor cursor = AdviceManager.getInstance(getApplicationContext()).getLastAdviceCursor();
//				Looper.prepare();
////				if(adapter == null)
////					Log.v("showNewAdvice: before sending message", "adapter is null");
////				else
////					Log.v("showNewAdvice: before sending message", "adapter is"+adapter);
//				adapter.changeCursor(cursor);
////				= new SimpleCursorAdapter(getApplicationContext(),
////						android.R.layout.simple_list_item_1, cursor, 
////						new String[]{AdviceProvider.COLUMN_NAMES[AdviceProvider.PRODUCT_NAME]},
////						new int[]{android.R.id.text1});
//				if(adapter == null)
//					Log.v("showNewAdvice: before sending message", "adapter is null");
//				else
//					Log.v("showNewAdvice: before sending message", "adapter is"+adapter);
				m = Message.obtain(handler, AdviceRequestHandler.READY);
				m.sendToTarget();
			}
		});
		
		t.start();
	}
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
//            Log.e(TAG, "bad menuInfo", e);
            return;
        }

        Cursor cursor = (Cursor)adapter.getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }
        menu.setHeaderTitle(cursor.getString(0));
		menu.add(0, MENU_ITEM_ADD_TO_EATEN, 0, R.string.context_menu_add_to_eaten);

	}
    public boolean onContextItemSelected(MenuItem item){
    	final AdapterView.AdapterContextMenuInfo info;
//    	ProfileManager profileManager = ProfileManager.getInstance(getApplicationContext());
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
//            Log.e(TAG, "bad menuInfo", e);
            return false;
        }
        
        switch (item.getItemId()) {
            case MENU_ITEM_ADD_TO_EATEN: 
            	AdviceManager adviceManager = AdviceManager.getInstance(getApplicationContext());
            	adviceManager.moveFromAdviceToEaten((int)info.id);
            	adapter.changeCursor(adviceManager.getLastAdviceCursor());
        		return true;
        }
        return false;
    }
}
